package com.lixin.rabbitmq.service;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class OrderService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    public String create() {
        String orderId = UUID.randomUUID().toString();
        String exchangeName = "fanout_order_exchange";
        String routingKey = "";

        // 设置消息的属性
        MessagePostProcessor processor = new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                // 消息存活时间为5秒，5秒后还没有被消费掉，就自动被删除
                message.getMessageProperties().setExpiration("5000");
                // 消息的编码方式为UTF-8
                message.getMessageProperties().setContentEncoding("UTF-8");
                return message;
            }
        };

        /*RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                if (correlationData != null) {
                    System.out.println(correlationData.getId() + ":" + b);
                }
            }
        };
        rabbitTemplate.setConfirmCallback(confirmCallback);
*/
        rabbitTemplate.convertAndSend(exchangeName, routingKey, orderId, processor);
        //rabbitTemplate.convertAndSend(exchangeName, routingKey, orderId, processor, new CorrelationData(UUID.randomUUID().toString()));
        return "订单:" + orderId + "已生成";
    }

    public String directCreate() {
        String orderId = UUID.randomUUID().toString();
        String exchangeName = "direct_order_exchange";
        String smsRoutingKey = "sms";
        rabbitTemplate.convertAndSend(exchangeName, smsRoutingKey, orderId);
        String wechatRoutingKey = "wechat";
        rabbitTemplate.convertAndSend(exchangeName, wechatRoutingKey, orderId);
        return "订单:" + orderId + "已生成";
    }

    public String topicCreate() {
        String orderId = UUID.randomUUID().toString();
        String exchangeName = "topic_order_exchange";
        String routingKey = "sms.wechat.email";
        rabbitTemplate.convertAndSend(exchangeName, routingKey, orderId);
        return "订单:" + orderId + "已生成";
    }

}
